import React, { useState, useEffect } from 'react';
import { 
  IonPage, 
  IonContent, 
  IonHeader, 
  IonToolbar, 
  IonButtons, 
  IonMenuButton, 
  IonTitle,
  IonSearchbar,
  IonList,
  IonItem,
  IonAvatar,
  IonLabel,
  IonNote,
  IonBadge,
  IonButton,
  IonIcon,
  IonFab,
  IonFabButton,
  useIonViewWillEnter
} from '@ionic/react';
import { 
  add, 
  search, 
  paperPlane, 
  ellipsisHorizontal,
  time,
  personCircleOutline,
  checkmarkDone,
  arrowBack
} from 'ionicons/icons';
import { useHistory } from 'react-router-dom';
import './MessagesPage.css';

// 消息类型定义
interface Message {
  id: string;
  sender: string;
  avatar: string;
  lastMessage: string;
  timestamp: string;
  unread: number;
  online: boolean;
}

// 聊天消息类型
interface ChatMessage {
  id: string;
  sender: string;
  avatar: string;
  content: string;
  timestamp: string;
  isMe: boolean;
  read: boolean;
}

const MessagesPage: React.FC = () => {
  const history = useHistory();
  const [searchText, setSearchText] = useState('');
  const [messages, setMessages] = useState<Message[]>([]);
  const [filteredMessages, setFilteredMessages] = useState<Message[]>([]);
  const [activeChat, setActiveChat] = useState<string | null>(null);
  const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);
  const [newMessage, setNewMessage] = useState('');

  // 模拟加载消息数据
  const loadMessages = () => {
    const mockMessages: Message[] = [
      {
        id: '1',
        sender: '张三',
        avatar: 'https://i.pravatar.cc/150?img=1',
        lastMessage: '你好，最近怎么样？',
        timestamp: '10:30',
        unread: 2,
        online: true
      },
      {
        id: '2',
        sender: '李四',
        avatar: 'https://i.pravatar.cc/150?img=2',
        lastMessage: '项目进展顺利吗？',
        timestamp: '昨天',
        unread: 0,
        online: false
      },
      {
        id: '3',
        sender: '王五',
        avatar: 'https://i.pravatar.cc/150?img=3',
        lastMessage: '会议安排在下午3点',
        timestamp: '昨天',
        unread: 1,
        online: true
      },
      {
        id: '4',
        sender: '赵六',
        avatar: 'https://i.pravatar.cc/150?img=4',
        lastMessage: '文档已经发给你了',
        timestamp: '周三',
        unread: 0,
        online: false
      },
      {
        id: '5',
        sender: '钱七',
        avatar: 'https://i.pravatar.cc/150?img=5',
        lastMessage: '周末一起吃饭吗？',
        timestamp: '周二',
        unread: 0,
        online: true
      },
      {
        id: '6',
        sender: '孙八',
        avatar: 'https://i.pravatar.cc/150?img=6',
        lastMessage: '设计稿已经完成了',
        timestamp: '周一',
        unread: 3,
        online: false
      },
      {
        id: '7',
        sender: '周九',
        avatar: 'https://i.pravatar.cc/150?img=7',
        lastMessage: '需要你的反馈意见',
        timestamp: '周一',
        unread: 0,
        online: true
      }
    ];
    
    setMessages(mockMessages);
    setFilteredMessages(mockMessages);
  };

  // 模拟加载聊天消息
  const loadChatMessages = (chatId: string) => {
    const mockChatMessages: ChatMessage[] = [
      {
        id: '1',
        sender: '张三',
        avatar: 'https://i.pravatar.cc/150?img=1',
        content: '你好，最近怎么样？',
        timestamp: '10:30',
        isMe: false,
        read: true
      },
      {
        id: '2',
        sender: '我',
        avatar: 'https://i.pravatar.cc/150?img=12',
        content: '挺好的，项目进展顺利',
        timestamp: '10:31',
        isMe: true,
        read: true
      },
      {
        id: '3',
        sender: '张三',
        avatar: 'https://i.pravatar.cc/150?img=1',
        content: '那太好了，我们什么时候讨论一下下一步计划？',
        timestamp: '10:32',
        isMe: false,
        read: true
      },
      {
        id: '4',
        sender: '我',
        avatar: 'https://i.pravatar.cc/150?img=12',
        content: '明天下午2点怎么样？',
        timestamp: '10:33',
        isMe: true,
        read: true
      },
      {
        id: '5',
        sender: '张三',
        avatar: 'https://i.pravatar.cc/150?img=1',
        content: '可以，地点定在哪里？',
        timestamp: '10:34',
        isMe: false,
        read: true
      },
      {
        id: '6',
        sender: '我',
        avatar: 'https://i.pravatar.cc/150?img=12',
        content: '老地方，咖啡厅见',
        timestamp: '10:35',
        isMe: true,
        read: true
      }
    ];
    
    setChatMessages(mockChatMessages);
  };

  // 页面加载时获取消息
  useIonViewWillEnter(() => {
    loadMessages();
  });

  // 搜索联系人
  useEffect(() => {
    if (searchText.trim() === '') {
      setFilteredMessages(messages);
    } else {
      const searchLower = searchText.toLowerCase();
      const filtered = messages.filter(
        msg => msg.sender.toLowerCase().includes(searchLower)
      );
      setFilteredMessages(filtered);
    }
  }, [searchText, messages]);

  // 打开聊天
  const openChat = (chatId: string) => {
    setActiveChat(chatId);
    loadChatMessages(chatId);
    
    // 清除未读消息
    setMessages(messages.map(msg => 
      msg.id === chatId ? { ...msg, unread: 0 } : msg
    ));
  };

  // 关闭聊天
  const closeChat = () => {
    setActiveChat(null);
    setChatMessages([]);
  };

  // 发送消息
  const sendMessage = () => {
    if (newMessage.trim() === '') return;
    
    const newMsg: ChatMessage = {
      id: Date.now().toString(),
      sender: '我',
      avatar: 'https://i.pravatar.cc/150?img=12',
      content: newMessage,
      timestamp: '刚刚',
      isMe: true,
      read: false
    };
    
    setChatMessages([...chatMessages, newMsg]);
    setNewMessage('');
    
    // 模拟对方回复
    setTimeout(() => {
      const replyMsg: ChatMessage = {
        id: Date.now().toString(),
        sender: messages.find(m => m.id === activeChat)?.sender || '对方',
        avatar: messages.find(m => m.id === activeChat)?.avatar || '',
        content: '收到，谢谢！',
        timestamp: '刚刚',
        isMe: false,
        read: false
      };
      
      setChatMessages(prev => [...prev, replyMsg]);
    }, 1000);
  };

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonButtons slot="start">
            <IonMenuButton />
          </IonButtons>
          
          <IonTitle>消息</IonTitle>
          
          <IonButtons slot="end">
            <IonButton>
              <IonIcon slot="icon-only" icon={ellipsisHorizontal} />
            </IonButton>
          </IonButtons>
        </IonToolbar>
        
        {/* 搜索栏 */}
        <IonToolbar>
          <IonSearchbar 
            placeholder="搜索联系人" 
            value={searchText}
            onIonChange={e => setSearchText(e.detail.value!)}
            animated
          />
        </IonToolbar>
      </IonHeader>
      
      <IonContent className="ion-padding">
        {/* 聊天界面 */}
        {activeChat ? (
          <div className="chat-container">
            {/* 聊天头部 */}
            <div className="chat-header">
              <IonButton fill="clear" onClick={closeChat}>
                <IonIcon slot="icon-only" icon={arrowBack} />
              </IonButton>
              
              <IonAvatar className="chat-avatar">
                <img 
                  src={messages.find(m => m.id === activeChat)?.avatar} 
                  alt="联系人头像" 
                />
                {messages.find(m => m.id === activeChat)?.online && (
                  <span className="online-badge"></span>
                )}
              </IonAvatar>
              
              <div className="chat-info">
                <IonLabel className="chat-name">
                  {messages.find(m => m.id === activeChat)?.sender}
                </IonLabel>
                <IonNote className="chat-status">
                  {messages.find(m => m.id === activeChat)?.online ? '在线' : '离线'}
                </IonNote>
              </div>
              
              <IonButton fill="clear">
                <IonIcon slot="icon-only" icon={ellipsisHorizontal} />
              </IonButton>
            </div>
            
            {/* 聊天内容 */}
            <div className="chat-messages">
              {chatMessages.map(message => (
                <div 
                  key={message.id} 
                  className={`message ${message.isMe ? 'sent' : 'received'}`}
                >
                  {!message.isMe && (
                    <IonAvatar className="message-avatar">
                      <img src={message.avatar} alt={message.sender} />
                    </IonAvatar>
                  )}
                  
                  <div className="message-content">
                    <div className="message-text">{message.content}</div>
                    <div className="message-time">
                      <IonIcon icon={time} size="small" />
                      {message.timestamp}
                    </div>
                  </div>
                  
                  {message.isMe && (
                    <div className="message-status">
                      {message.read ? (
                        <IonIcon icon={checkmarkDone} color="primary" />
                      ) : (
                        <IonIcon icon={checkmarkDone} color="medium" />
                      )}
                    </div>
                  )}
                </div>
              ))}
            </div>
            
            {/* 消息输入框 */}
            <div className="message-input">
              <IonSearchbar 
                placeholder="输入消息..." 
                value={newMessage}
                onIonChange={e => setNewMessage(e.detail.value!)}
                onKeyPress={e => e.key === 'Enter' && sendMessage()}
                className="message-input-field"
              />
              
              <IonButton 
                fill="clear" 
                color="primary" 
                onClick={sendMessage}
                disabled={newMessage.trim() === ''}
              >
                <IonIcon icon={paperPlane} />
              </IonButton>
            </div>
          </div>
        ) : (
          // 消息列表
          <IonList lines="full" className="message-list">
            {filteredMessages.length > 0 ? (
              filteredMessages.map(message => (
                <IonItem 
                  key={message.id} 
                  button 
                  detail={false}
                  onClick={() => openChat(message.id)}
                  className={message.unread > 0 ? 'unread' : ''}
                >
                  <IonAvatar slot="start" className="message-avatar">
                    <img src={message.avatar} alt={message.sender} />
                    {message.online && <span className="online-badge"></span>}
                  </IonAvatar>
                  
                  <IonLabel className="ion-text-wrap">
                    <h2>{message.sender}</h2>
                    <p>{message.lastMessage}</p>
                  </IonLabel>
                  
                  <IonNote slot="end" className="message-meta">
                    <div className="message-time">{message.timestamp}</div>
                    {message.unread > 0 && (
                      <IonBadge color="primary">{message.unread}</IonBadge>
                    )}
                  </IonNote>
                </IonItem>
              ))
            ) : (
              <div className="empty-state">
                <IonIcon icon={personCircleOutline} size="large" color="medium" />
                <h3>没有消息</h3>
                <p>您当前没有消息记录</p>
              </div>
            )}
          </IonList>
        )}
        
        {/* 新建聊天按钮 */}
        {!activeChat && (
          <IonFab vertical="bottom" horizontal="end" slot="fixed">
            <IonFabButton color="primary" routerLink="/contacts">
              <IonIcon icon={add} />
            </IonFabButton>
          </IonFab>
        )}
      </IonContent>
    </IonPage>
  );
};

export default MessagesPage;